package neu.edu.cn.nuemall.controller;

import com.github.pagehelper.PageInfo;
import neu.edu.cn.nuemall.entity.ShippingAddress;
import neu.edu.cn.nuemall.entity.Userinfo;
import neu.edu.cn.nuemall.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class AddressController {

    @Autowired
    private AddressService addressService;

    @GetMapping("/getAddressList")
    public String getAddressList(Model model,
                                 @RequestParam(value = "page",defaultValue = "1") Integer page,
                                 @RequestParam(value = "count",defaultValue = "6") Integer count,
                                 HttpSession session){
        Userinfo user=(Userinfo) session.getAttribute("USER_INFO");
        if (user!=null){
            PageInfo<ShippingAddress> addressList=addressService.getAddressList(page,count,user.getId());
            model.addAttribute("addressList",addressList);
        }
        return "/address/addressList";
    }

    @PostMapping("/addAddress")
    public String putShippingAddress(ShippingAddress address, HttpSession session){
        Userinfo user=(Userinfo) session.getAttribute("USER_INFO");
        if (user!=null){
            address.setUserId(user.getId());
            String id=address.getId();
            if (StringUtils.isEmpty(id)){
                addressService.insertAddress(address);
            }else {
                addressService.updateAddress(address);
            }
        }
        return "redirect:/getAddressList";
    }
    @PostMapping("/deleteAddress")
    public String delShippingAddress(ShippingAddress address,HttpSession session){
        Userinfo user=(Userinfo) session.getAttribute("USER_INFO");
        if (user!=null) {
            address.setUserId(user.getId());
            String id = address.getId();
            addressService.delectAddress(address);
        }
        return "redirect:/getAddressList";
    }
}
